﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Enums;
using DeviceCommons.DeviceMessages.Models.V1;

namespace DeviceCommons.DeviceMessages.Serialization.V2.Parsers
{
    public class DeviceMessageInfoReadingStateParser : AbstractMessageParser<IDeviceMessageInfoReadingState>, IDeviceMessageInfoReadingStateParser
    {
        public DeviceMessageInfoReadingStateParser() : base(new DeviceMessageInfoReadingState())
        {
        }

        public override IDeviceMessageInfoReadingState Parser(ReadOnlySpan<byte> bytes)
        {
            IDeviceMessageInfoReadingState model = new DeviceMessageInfoReadingState
            {
                SID = bytes[0],
                Type = bytes[1]
            };
            StateValueTypeEnum type = (StateValueTypeEnum)bytes[1];
            var valueLength = DeviceMessageUtilities.GetValueLength((StateValueTypeEnum)bytes[1], bytes, 2);
            if(type == StateValueTypeEnum.String)
            {
                model.Value = bytes.Slice(3, valueLength).ToArray();
            }
            else if(type == StateValueTypeEnum.Binary)
            {
                model.Value = bytes.Slice(4, valueLength).ToArray();
            }
            else
            {
                model.Value = bytes.Slice(2, valueLength).ToArray();
            }
            Model = model;
            return model;
        }
    }
}
